package util

import (
	"fmt"
	"io/ioutil"
	"log"
	"mumu_stock_trad/model"
	"net/http"
	"strconv"
	"strings"
	"time"

	"golang.org/x/net/html/charset"
)

const (
	apiQtURL = "http://qt.gtimg.cn/q=%s"
)

// FetchStockData 从 API 获取股票数据
func FetchStockDataQtAll(symbol string) ([]model.StockDataQT, error) {
	url := fmt.Sprintf(apiQtURL, symbol)
	// 发起 HTTP 请求获取数据
	resp, err := http.Get(url)
	if err != nil {
		return []model.StockDataQT{}, fmt.Errorf("failed to fetch data from API: %v", err)
	}
	defer resp.Body.Close()

	// 使用charset.DetermineEncoding函数获取正确的字符编码
	reader, err := charset.NewReader(resp.Body, resp.Header.Get("Content-Type"))
	if err != nil {
		log.Fatalf("Error determining charset: %v", err)
	}

	// 读取 HTTP 响应体
	body, err := ioutil.ReadAll(reader)
	if err != nil {
		return []model.StockDataQT{}, fmt.Errorf("failed to read response body: %v", err)
	}

	// 解析返回的数据
	stockData := string(body)
	// 假设数据以行为单位，每行使用 | 分割不同的数据项
	lines := strings.Split(stockData, "\n")

	stock := []model.StockDataQT{}
	// 遍历每行数据
	for _, line := range lines {
		if line == "" {
			continue
		}

		// 假设数据项之间使用 ~ 分隔，解析每个数据项
		dataItems := strings.Split(line, "~")
		if len(dataItems) < 49 { // 根据具体情况调整数据项的个数
			continue
		}

		// 创建StockData对象并赋值
		stocks := model.StockDataQT{
			StockCode:              dataItems[2], // 股票代码
			StockName:              dataItems[1], // 股票名称
			CurrentPrice:           parseFloat(dataItems[3]),
			YesterdayClosePrice:    parseFloat(dataItems[4]),
			TodayOpenPrice:         parseFloat(dataItems[5]),
			Volume:                 parseInt(dataItems[6]),
			OuterDisk:              parseInt(dataItems[7]),
			InnerDisk:              parseInt(dataItems[8]),
			BuyOnePrice:            parseFloat(dataItems[9]),
			BuyOneVolume:           parseInt(dataItems[10]),
			BuyTwoPrice:            parseFloat(dataItems[11]),
			BuyTwoVolume:           parseInt(dataItems[12]),
			BuyThreePrice:          parseFloat(dataItems[13]),
			BuyThreeVolume:         parseInt(dataItems[14]),
			BuyFourPrice:           parseFloat(dataItems[15]),
			BuyFourVolume:          parseInt(dataItems[16]),
			BuyFivePrice:           parseFloat(dataItems[17]),
			BuyFiveVolume:          parseInt(dataItems[18]),
			SellOnePrice:           parseFloat(dataItems[19]),
			SellOneVolume:          parseInt(dataItems[20]),
			SellTwoPrice:           parseFloat(dataItems[21]),
			SellTwoVolume:          parseInt(dataItems[22]),
			SellThreePrice:         parseFloat(dataItems[23]),
			SellThreeVolume:        parseInt(dataItems[24]),
			SellFourPrice:          parseFloat(dataItems[25]),
			SellFourVolume:         parseInt(dataItems[26]),
			SellFivePrice:          parseFloat(dataItems[27]),
			SellFiveVolume:         parseInt(dataItems[28]),
			LatestTransaction:      dataItems[29],
			TransactionTime:        dataItems[30],
			ChangeAmount:           parseFloat(dataItems[31]),
			ChangePercent:          parseFloat(dataItems[32]),
			HighestPrice:           parseFloat(dataItems[33]),
			LowestPrice:            parseFloat(dataItems[34]),
			BuySellPriceVolumeBuy:  parseFloat(dataItems[35]),
			BuySellPriceVolumeSell: parseFloat(dataItems[36]),
			TurnoverAmount:         parseFloat(dataItems[37]),
			TurnoverVolume:         parseInt(dataItems[38]),
			PERatio:                parseFloat(dataItems[39]),
			Capitalization:         parseFloat(dataItems[40]),
			TotalMarketValue:       parseFloat(dataItems[41]),
			CirculatingMarketValue: parseFloat(dataItems[42]),
			Amplitude:              parseFloat(dataItems[43]),
			TurnoverRate:           parseFloat(dataItems[44]),
			PBRatio:                parseFloat(dataItems[45]),
			CommissionRatio:        parseFloat(dataItems[46]),
			VolumeRatio:            parseFloat(dataItems[47]),
			CreatedAt:              time.Now(),
			UpdatedAt:              time.Now(),
		}

		stock = append(stock, stocks)
	}

	return stock, nil
}

// FetchStockData 从 API 获取股票数据
func FetchStockDataQt(symbol string) (model.StockDataQT, error) {
	url := fmt.Sprintf(apiQtURL, symbol)

	// 发起 HTTP 请求获取数据
	resp, err := http.Get(url)
	if err != nil {
		return model.StockDataQT{}, fmt.Errorf("failed to fetch data from API: %v", err)
	}
	defer resp.Body.Close()

	// 使用charset.DetermineEncoding函数获取正确的字符编码
	reader, err := charset.NewReader(resp.Body, resp.Header.Get("Content-Type"))
	if err != nil {
		log.Fatalf("Error determining charset: %v", err)
	}

	// 读取 HTTP 响应体
	body, err := ioutil.ReadAll(reader)
	if err != nil {
		return model.StockDataQT{}, fmt.Errorf("failed to read response body: %v", err)
	}

	// 解析返回的数据
	stockData := string(body)
	// 假设数据以行为单位，每行使用 | 分割不同的数据项
	lines := strings.Split(stockData, "\n")

	fmt.Println(stockData)
	stock := model.StockDataQT{}
	// 遍历每行数据
	for _, line := range lines {
		if line == "" {
			continue
		}

		// 假设数据项之间使用 ~ 分隔，解析每个数据项
		dataItems := strings.Split(line, "~")
		if len(dataItems) < 49 { // 根据具体情况调整数据项的个数
			continue
		}
		// 创建StockData对象并赋值
		stock = model.StockDataQT{
			StockCode:              dataItems[2], // 股票代码
			StockName:              dataItems[1], // 股票名称
			CurrentPrice:           parseFloat(dataItems[3]),
			YesterdayClosePrice:    parseFloat(dataItems[4]),
			TodayOpenPrice:         parseFloat(dataItems[5]),
			Volume:                 parseInt(dataItems[6]),
			OuterDisk:              parseInt(dataItems[7]),
			InnerDisk:              parseInt(dataItems[8]),
			BuyOnePrice:            parseFloat(dataItems[9]),
			BuyOneVolume:           parseInt(dataItems[10]),
			BuyTwoPrice:            parseFloat(dataItems[11]),
			BuyTwoVolume:           parseInt(dataItems[12]),
			BuyThreePrice:          parseFloat(dataItems[13]),
			BuyThreeVolume:         parseInt(dataItems[14]),
			BuyFourPrice:           parseFloat(dataItems[15]),
			BuyFourVolume:          parseInt(dataItems[16]),
			BuyFivePrice:           parseFloat(dataItems[17]),
			BuyFiveVolume:          parseInt(dataItems[18]),
			SellOnePrice:           parseFloat(dataItems[19]),
			SellOneVolume:          parseInt(dataItems[20]),
			SellTwoPrice:           parseFloat(dataItems[21]),
			SellTwoVolume:          parseInt(dataItems[22]),
			SellThreePrice:         parseFloat(dataItems[23]),
			SellThreeVolume:        parseInt(dataItems[24]),
			SellFourPrice:          parseFloat(dataItems[25]),
			SellFourVolume:         parseInt(dataItems[26]),
			SellFivePrice:          parseFloat(dataItems[27]),
			SellFiveVolume:         parseInt(dataItems[28]),
			LatestTransaction:      dataItems[29],
			TransactionTime:        dataItems[30],
			ChangeAmount:           parseFloat(dataItems[31]),
			ChangePercent:          parseFloat(dataItems[32]),
			HighestPrice:           parseFloat(dataItems[33]),
			LowestPrice:            parseFloat(dataItems[34]),
			BuySellPriceVolumeBuy:  parseFloat(dataItems[35]),
			BuySellPriceVolumeSell: parseFloat(dataItems[36]),
			TurnoverAmount:         parseFloat(dataItems[37]),
			TurnoverVolume:         parseInt(dataItems[38]),
			PERatio:                parseFloat(dataItems[39]),
			Capitalization:         parseFloat(dataItems[40]),
			TotalMarketValue:       parseFloat(dataItems[41]),
			CirculatingMarketValue: parseFloat(dataItems[42]),
			Amplitude:              parseFloat(dataItems[43]),
			TurnoverRate:           parseFloat(dataItems[44]),
			PBRatio:                parseFloat(dataItems[45]),
			CommissionRatio:        parseFloat(dataItems[46]),
			VolumeRatio:            parseFloat(dataItems[47]),
			CreatedAt:              time.Now(),
			UpdatedAt:              time.Now(),
		}

		fmt.Println("LatestTransaction:" + dataItems[29])
		fmt.Println(parseFloat(dataItems[35]))
		fmt.Println(parseFloat(dataItems[40]))
	}

	fmt.Println(stock)

	return stock, nil
}

// 辅助函数：将字符串解析为浮点数
func parseFloat(s string) float64 {
	result, _ := strconv.ParseFloat(s, 64)
	return result
}

// 辅助函数：将字符串解析为整数
func parseInt(s string) int {
	result, _ := strconv.Atoi(s)
	return result
}
